#include "InetAddress.h"
#include "Logger.h"
#include "TcpServer.h"
#include <thread>
#include <chrono>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>

using namespace GiSo;

// 客户端连接函数
// 客户端连接函数
void clientThreadFunc(const InetAddress& serverAddr) {
    try {
        // 等待一小会儿确保服务器已启动
        std::this_thread::sleep_for(std::chrono::milliseconds(100));
        
        // 创建客户端 socket
        int clientFd = socket(AF_INET, SOCK_STREAM, 0);
        if (clientFd < 0) {
            GS_ERROR("Failed to create client socket: {0}", strerror(errno));
            return;
        }

        // 构造 sockaddr_in 结构
        struct sockaddr_in addr;
        memset(&addr, 0, sizeof(addr));         // 清零结构
        addr.sin_family = AF_INET;              // IPv4
        addr.sin_port = htons(serverAddr.GetPort());  // 端口号转换为网络字节序
        
        // 处理 IP 地址
        std::string ip = serverAddr.GetIp();
        if (ip.empty()) {
            // 如果 IP 为空（只用了端口构造函数），默认使用 localhost
            ip = "127.0.0.1";
        }
        if (inet_pton(AF_INET, ip.c_str(), &addr.sin_addr) <= 0) {
            GS_ERROR("Invalid IP address: {0}", ip);
            close(clientFd);
            return;
        }

        // 连接到服务器
        int ret = connect(clientFd, (struct sockaddr*)&addr, sizeof(addr));
        if (ret < 0) {
            GS_ERROR("Failed to connect to server: {0}", strerror(errno));
            close(clientFd);
            return;
        }

        GS_INFO("Client connected successfully to {0}:{1}", ip, serverAddr.GetPort());

        // 模拟一些操作
        std::this_thread::sleep_for(std::chrono::seconds(1));

        // 发送一些数据
        const char* msg = "Hello from client!";
        for(int i = 0; i < 5; ++i) {
            send(clientFd, msg, strlen(msg), 0);
            GS_INFO("client sending data: {0}", i);
            std::this_thread::sleep_for(std::chrono::seconds(1));
        }
        
        close(clientFd);
        GS_INFO("Client disconnected");
    }
    catch (const std::exception& e) {
        GS_ERROR("Client thread error: {0}", e.what());
    }
}


int main() {
    GiSo::Logger::Options options;
    options.outputType = GiSo::Logger::OutputType::Both;
    options.filename = "my_app.log";
    GiSo::Logger::init(options);

    InetAddress addr(1126);
    TcpServer server(addr, 3);

    // 创建客户端线程
    std::thread clientThread(clientThreadFunc, std::ref(addr));
    std::thread clientThread2(clientThreadFunc, std::ref(addr));
    
    // read callback
    auto readCallback = [](TcpConnection::Ptr conn, Buffer& buffer) {
        if (conn){
            std::string data = buffer.CopyToString();
            GS_INFO("Received data: {0}", data);
            buffer.Clear();
        }
    };

    // 可选：设置连接回调来验证连接
    server.SetNewConnectionCallback(
        [readCallback](std::shared_ptr<TcpConnection> conn, const InetAddress& clientAddr) {
            GS_INFO("New connection from {0}:{1}", clientAddr.GetIp(),clientAddr.GetPort());
            conn->SetReadCallback(readCallback);
            conn->EnableReading();
            return true;
        }
    );

    // 启动服务器
    server.Start();

    return 0;
}